package by.amakarevich.webapp.page.thread.panel;

import java.util.Iterator;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import by.amakarevich.datamodel.Product;
import by.amakarevich.datamodel.Product_;
import by.amakarevich.datamodel.ShoppingCart;
import by.amakarevich.datamodel.ShoppingCartInfo;
import by.amakarevich.datamodel.Thread;
import by.amakarevich.datamodel.UserAccount;
import by.amakarevich.datamodel.enums.Category;
import by.amakarevich.services.ProductService;
import by.amakarevich.services.ShoppingCartInfoService;
import by.amakarevich.services.ShoppingCartService;
import by.amakarevich.services.ThreadService;
import by.amakarevich.webapp.app.BasicAuthenticationSession;
import by.amakarevich.webapp.app.SecuredLinkForAdmin;
import by.amakarevich.webapp.page.MyPagingNavigator;
import by.amakarevich.webapp.page.edit.ProductCreateEditPage;
import by.amakarevich.webapp.page.login.LoginPage;

public class ThreadListPanel extends Panel {

	@Inject
	private ProductService productService;
	@Inject
	private ThreadService threadService;
	@Inject
	private ShoppingCartService shoppingCartService;
	@Inject
	private ShoppingCartInfoService shoppingCartInfoService;

	public ThreadListPanel(String id) {
		super(id);
		setOutputMarkupId(true);
		ProductDataProvider productDataProvider = new ProductDataProvider();

		final WebMarkupContainer tableBody = new WebMarkupContainer("wrapper-body") {
			@Override
			protected void onBeforeRender() {
				super.onBeforeRender();
				add(new AttributeModifier("title", new Model(System.currentTimeMillis())));
			}
		};

		tableBody.add(new AttributeModifier("title", new Model(System.currentTimeMillis())));

		tableBody.setOutputMarkupId(true);
		add(tableBody);

		DataView<Product> dataView = new DataView<Product>("list", productDataProvider, 15) {
			@Override
			protected void populateItem(Item<Product> item) {
				final Product product = item.getModelObject();
				item.add(new Label("item"));
				item.add(new Label("company"));
				item.add(new Label("price"));
				item.add(new Label("available"));
				final Thread thread= threadService.getByProductId(product);
				item.add(new Label("color", new Model<String>(thread.getColor())));

				Link<Void> securedEditLink = new SecuredLinkForAdmin("product-edit-page-link") {

					@Override
					public void onClick() {
						setResponsePage(new ProductCreateEditPage(product));

					}
				};
				
				item.add(securedEditLink);
				
				item.add(new AjaxLink<Void>("product-to-shopping-cart-link") {
					@Override
					public void onClick(AjaxRequestTarget target) {
						if(BasicAuthenticationSession.get().getUser()!=null){
							UserAccount user= BasicAuthenticationSession.get().getUser();
						
							ShoppingCart shoppingCart = shoppingCartService.getByUser(user) ;
						
						
							ShoppingCartInfo shoppingCartInfo = new ShoppingCartInfo();
							if(shoppingCartInfoService.getShoppingCartInfo(shoppingCart, product)==null){
								shoppingCartInfo.setQuantity(1l);
								shoppingCartInfo.setPrice(product.getPrice());
								shoppingCartInfoService.addNewShoppingCartInfo(shoppingCartInfo, product, shoppingCart);
							}else{
								shoppingCartInfo=shoppingCartInfoService.getShoppingCartInfo(shoppingCart, product);
								shoppingCartInfo.setQuantity(shoppingCartInfo.getQuantity()+1);
								shoppingCartInfoService.updateShoppingCartInfo(shoppingCartInfo);						
							}
							Page page = getPage();

							page.info("Артикул добавлен в корзину");

							setResponsePage(page);
							
						}else{
							setResponsePage(new LoginPage());
						}
						target.add(ThreadListPanel.this);
					}
				});

			}
		};

		tableBody.add(dataView);

		add(new MyPagingNavigator("paging", dataView));


		add(new OrderByBorder<SingularAttribute<Product, ?>>("sortByCompany", Product_.company, productDataProvider));
		add(new OrderByBorder<SingularAttribute<Product, ?>>("sortByPrice", Product_.price, productDataProvider));
		

	
	}
	private class ProductDataProvider extends SortableDataProvider<Product, SingularAttribute<Product, ?>> {

		public ProductDataProvider() {
			super();
			setSort(Product_.id, SortOrder.ASCENDING);
		}

		@Override
		public Iterator<? extends Product> iterator(long first, long count) {

			SingularAttribute<Product, ?> sortParam = getSort().getProperty();
			SortOrder propertySortOrder = getSortState().getPropertySortOrder(sortParam);
			boolean ascending = SortOrder.ASCENDING.equals(propertySortOrder);
			return productService.getSortedAllProduct(sortParam, ascending, (int) first, (int) count, Category.thread).iterator();
		}

		@Override
		public long size() {
			return productService.getCount(Category.thread);
		}

		public IModel<Product> model(Product product) {
			return new CompoundPropertyModel<Product>(product);
		}
	}

}
